package dal

import (
	"starry_sky/internal/config"
	"starry_sky/internal/core"
	"starry_sky/internal/model"
	"starry_sky/internal/tools/encryption"
	"starry_sky/internal/tools/logger"
)

func InitTableAndData() {
	logger.SysInfoF("初始化系统表")
	// 开发中新增的表 将部分注解放开即可动态增加或重置
	err := DB.AutoMigrate(
		&model.User{},
		&model.Role{},
		&model.Permission{},
		&model.TemplateStruct{},
		&model.TemplateAttribute{},
		&model.DictType{},
		&model.DictData{},
		&model.LoginLog{},
	)

	if logger.HasError(err) {
		panic("数据库初始化错误")
	}
	var countAdmin int64
	err = CountByMap[model.User](&countAdmin, map[string]any{"username": "admin"})
	if logger.HasError(err) {
		panic("初始化过程中-管理员数据库查询错误")
	}
	if countAdmin == 0 {
		//启动初始化用户权限插入事务
		tx := TransactionBegin()
		admin := model.User{
			Username: "admin",
			Password: encryption.MD5(core.DefaultPassword),
			Nickname: "管理员",
			Remark:   "超级管理员",
			Email:    "",
			Mobile:   "",
			Sex:      0,
			Avatar:   "",
			Status:   true,
		}
		err = TransactionInsert(tx, &admin)
		if logger.HasError(err) {
			err = TransactionRollback(tx)
			if logger.HasError(err) {
				logger.SysErrorF("事务回滚失败")
			}
			panic("超级管理员用户创建失败")
		}
		adminRole := model.Role{
			Creator:   "",
			Updater:   "",
			Name:      "超级管理员",
			Code:      "super_admin",
			Sort:      0,
			DataScope: 0,
			Status:    true,
			Type:      0,
			Remark:    "",
		}
		err = TransactionInsert(tx, &adminRole)
		if logger.HasError(err) {
			err = TransactionRollback(tx)
			if logger.HasError(err) {
				logger.SysErrorF("事务回滚失败")
			}
			panic("超级管理员角色创建失败")
		}
		err = tx.Model(&admin).Association("Roles").Append(&adminRole)
		if logger.HasError(err) {
			err = TransactionRollback(tx)
			if logger.HasError(err) {
				logger.SysErrorF("事务回滚失败")
			}
			panic("超级管理员用户角色关联失败")
		}
		systemPermission := model.Permission{
			Title:      "系统管理",
			Name:       "系统管理",
			Permission: "",
			Type:       core.Catalogue,
			ParentId:   "",
			Sort:       0,
			Icon:       "",
			Path:       "",
			Status:     true,
			KeepAlive:  true,
			Visible:    true,
		}
		err = TransactionInsert(tx, &systemPermission)
		if logger.HasError(err) {
			err = TransactionRollback(tx)
			if logger.HasError(err) {
				logger.SysErrorF("事务回滚失败")
			}
			panic("系统管理菜单创建")
		}
		userPermission := model.Permission{
			Title:      "用户管理",
			Name:       "用户管理",
			Permission: "",
			Type:       core.Menu,
			ParentId:   systemPermission.ID,
			Sort:       1,
			Icon:       "",
			Path:       "",
			Status:     true,
			KeepAlive:  true,
			Visible:    true,
		}
		err = TransactionInsert(tx, &userPermission)
		if logger.HasError(err) {
			err = TransactionRollback(tx)
			if logger.HasError(err) {
				logger.SysErrorF("事务回滚失败")
			}
			panic("用户管理菜单创建")
		}
		rolePermission := model.Permission{
			Title:      "角色管理",
			Name:       "角色管理",
			Permission: "",
			Type:       core.Menu,
			ParentId:   systemPermission.ID,
			Sort:       2,
			Icon:       "",
			Path:       "",
			Status:     true,
			KeepAlive:  true,
			Visible:    true,
		}
		err = TransactionInsert(tx, &rolePermission)
		if logger.HasError(err) {
			err = TransactionRollback(tx)
			if logger.HasError(err) {
				logger.SysErrorF("事务回滚失败")
			}
			panic("角色管理菜单创建")
		}
		permissionPermission := model.Permission{
			Title:      "权限管理",
			Name:       "权限管理",
			Permission: "",
			Type:       core.Menu,
			ParentId:   systemPermission.ID,
			Sort:       3,
			Icon:       "",
			Path:       "",
			Status:     true,
			KeepAlive:  true,
			Visible:    true,
		}
		err = TransactionInsert(tx, &permissionPermission)
		if logger.HasError(err) {
			err = TransactionRollback(tx)
			if logger.HasError(err) {
				logger.SysErrorF("事务回滚失败")
			}
			panic("权限管理菜单创建")
		}
		err = tx.Model(&adminRole).Association("Permissions").Append([]model.Permission{systemPermission, userPermission, rolePermission, permissionPermission})
		if logger.HasError(err) {
			err = TransactionRollback(tx)
			if logger.HasError(err) {
				logger.SysErrorF("事务回滚失败")
			}
			panic("超级管理员角色权限关联失败")
		}
		err = TransactionCommit(tx)
		if logger.HasError(err) {
			panic("事务提交失败")
		}
	}
	//  初始化完成更新数据库配置为不需要初始化
	config.DbConfig.NeedInit = false
	config.DbConfig.UpdateDbConfig()
}
